<template>
  <div class="analyze-container">
    <div class="header">
      <h2>巡更数据AI分析</h2>

      <el-select
          v-model="selectedCommunity"
          placeholder="选择小区"
          style="width: 200px; margin-right: 10px;"
      >
        <el-option
            v-for="community in communityList"
            :key="community.id"
            :label="community.name"
            :value="community.id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="analyzeData" :loading="loading">
        <el-icon><MagicStick /></el-icon>
        开始分析
      </el-button>
    </div>

    <!-- 图表容器 -->
    <div v-if="showChart" class="chart-container">
      <div v-for="(chart, index) in chartList" :key="index" :id="`chart-${index}`" style="width: 100%; height: 500px; margin-bottom: 30px;"></div>
    </div>
    <!-- 明细表格 -->
    <div v-if="detailTable" class="detail-table">
      <el-table :data="detailTableData" border style="width: 100%">
        <el-table-column
            v-for="column in detailTableColumns"
            :key="column.key"
            :prop="column.key"
            :label="column.title"
        ></el-table-column>
      </el-table>
    </div>
    <!-- 文本分析结果 -->
    <div v-if="analysisText" class="analysis-text" v-html="analysisText"></div>
  </div>
</template>

<script setup>
import { ref } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'
import { MagicStick } from '@element-plus/icons-vue'
import {ElMessage} from "element-plus";

const loading = ref(false)
const showChart = ref(false)
const chartList = ref([]) // 存储从接口获取的图表配置
const analysisText = ref('')
const chartInstances = ref({}) // 存储图表实例
const detailTable = ref(false)
const detailTableColumns = ref([])
const detailTableData = ref([])
const communityList = ref([
  { id: 1, name: '万象城' },
  { id: 2, name: '万达文旅城' },
  { id: 3, name: '碧桂园' }
])
const selectedCommunity = ref(1)

// AI分析数据
const analyzeData = async () => {
  loading.value = true
  showChart.value = false
  analysisText.value = ''
  chartList.value = [] // 清空图表列表

  try {
    const response = await axios.get('http://localhost:9031/analyze', {
      params: {
        apiUrl: `http://localhost:8009/patrol/plan/list?communityId=${selectedCommunity.value}`
      }
    })
    // 假设 response.data 是带 ```json 的字符串
    const jsonStr = response.data
        .replace(/```json/, '')
        .replace(/```/, '')
        .trim();

    const data = JSON.parse(jsonStr);
    console.log('AI分析结果:', data)
    processAnalysisResult(data);
  } catch (error) {
    console.error('请求失败:', error)
    ElMessage.error('分析失败，请重试')
  } finally {
    loading.value = false
  }
}

// 处理分析结果
const processAnalysisResult = (data) => {
  // 显示文本分析
  if (data.analysisText) {
    analysisText.value = formatAnalysisText(data.analysisText)
  }

  // 显示明细表格
  if (data.detailTable) {
    detailTable.value = true
    detailTableColumns.value = data.detailTable.columns || []
    detailTableData.value = data.detailTable.data || []
  }

  // 修复这里：从data.charts获取图表数据，而不是data.chartData
  if (data.charts && data.charts.length > 0) {
    chartList.value = data.charts
    showChart.value = true

    // 延迟执行以确保DOM已渲染
    setTimeout(() => {
      // 渲染所有图表
      chartList.value.forEach((chartData, index) => {
        renderChart(chartData, `chart-${index}`)
      })
    }, 100)
  }
}

// 格式化分析文本
const formatAnalysisText = (text) => {
  // 将分析文本中的加粗标记转换为HTML
  return text
      .replace(/\*\*(.*?)\*\*/g, '<strong>$1</strong>')
      .replace(/\n/g, '<br>')
}

// 渲染图表
const renderChart = (chartData, containerId) => {
  const chartDom = document.getElementById(containerId)
  if (!chartDom) {
    console.error(`找不到图表容器: ${containerId}`)
    return
  }

  const chartInstance = echarts.init(chartDom)

  // 从series数据中提取值
  const prepareSeriesData = (series) => {
    if (chartData.type === 'pie') {
      // 饼图数据格式正确，无需处理
      return series
    } else if (chartData.type === 'bar' || chartData.type === 'line') {
      // 对于bar和line图表，需要从data数组中的对象提取value值
      return series.map(serie => ({
        ...serie,
        data: serie.data.map(item => item.value)
      }))
    }
    return series
  }

  // 根据图表类型创建不同的配置
  let option
  if (chartData.type === 'pie') {
    option = {
      title: {
        text: chartData.title || '分析结果'
      },
      tooltip: {
        trigger: 'item'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: chartData.legend || []
      },
      series: prepareSeriesData(chartData.series).map(series => ({
        ...series,
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        }
      }))
    }
  } else if (chartData.type === 'bar') {
    option = {
      title: {
        text: chartData.title || '分析结果'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: chartData.legend || []
      },
      xAxis: chartData.xAxis,
      yAxis: {
        type: 'value'
      },
      series: prepareSeriesData(chartData.series).map(series => ({
        ...series,
        type: 'bar'
      }))
    }
  } else if (chartData.type === 'line') {
    option = {
      title: {
        text: chartData.title || '分析结果'
      },
      tooltip: {
        trigger: 'axis'
      },
      legend: {
        orient: 'vertical',
        left: 'left',
        data: chartData.legend || []
      },
      xAxis: chartData.xAxis,
      yAxis: {
        type: 'value'
      },
      series: prepareSeriesData(chartData.series).map(series => ({
        ...series,
        type: 'line'
      }))
    }
  } else {
    console.error(`不支持的图表类型: ${chartData.type}`)
    return
  }

  // 应用配置并保存实例
  chartInstance.setOption(option)
  chartInstances.value[containerId] = chartInstance
}
</script>

<style scoped>
.analyze-container {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.chart-container {
  margin-bottom: 30px;
}

.analysis-text {
  padding: 20px;
  background-color: #ffffff;
  border-left: 5px solid #409EFF;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
  font-size: 15px;
  line-height: 1.8;
  color: #333;
  white-space: pre-wrap;
  border-radius: 6px;
  margin-top: 20px;
  max-height: 600px;
  overflow-y: auto;
}

strong {
  color: #409EFF;
}
</style>
